package cn.shengchao.examstar.product.ohs.remote.rpc;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import cn.shengchao.examstar.product.acl.adapters.repositories.SpecificationTypeRepository;
import cn.shengchao.examstar.product.infrastructure.dao.po.TSpecificationType;
import cn.shengchao.examstar.rpc.base.TransResult;
import cn.shengchao.examstar.rpc.product.api.ISpecificationTypeRpc;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @program: examstarapi
 * @description: 课程类目数据操作rpc实现
 * @author: Xiong weiqiang
 * @create: 2025-05-21 11:42
 */
@DubboService
@RequiredArgsConstructor
public class SpecificationTypeRpc implements ISpecificationTypeRpc {
    private final  SpecificationTypeRepository specificationTypeRepository;
    @Transactional
    @Override
    public TransResult<String> sortSpecificationTypesBySameLevelIds(List<Long> specTypeIds) {
        List<TSpecificationType> specificationTypes = specificationTypeRepository.getSpecificationTypesByIdList(specTypeIds);
        List<Long> parentIds=specificationTypes.stream().map(a->ObjUtil.defaultIfNull(a.getParentId(),0L)).distinct().toList();
        if (CollUtil.isEmpty(parentIds) || parentIds.size()>1){
            return TransResult.fail("排序调整失败，请选择同一级类目调整");
        }else{
            List<TSpecificationType> parentSpecificationTypes = specificationTypeRepository.getSpecificationTypesByParentIdAndIdList(parentIds.getFirst(), specTypeIds);
            long i=1;
            System.out.println("排序："+ JSONUtil.toJsonStr(specTypeIds));
            for (Long specTypeId : specTypeIds){
               Optional<TSpecificationType> specificationType = parentSpecificationTypes.stream().filter(a->a.getId().equals(specTypeId)).findFirst();
               if (specificationType.isPresent()){
                   System.out.println("排序细节：名称："+ specificationType+",次序"+i);
                   specificationType.get().setSort(i++);
                   specificationTypeRepository.updateSpecificationTypeById(specificationType.get());
               }
            }
        }
        return TransResult.success("排序调整成功");
    }
}